package com.example.zhangwei.service;


import com.example.zhangwei.Constants;
import com.example.zhangwei.model.DataSerializable;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
	
	public static final String SEND_MY_SERVICE_DATA_EXECUTE = "android.intent.action.my_service_data_exectue"; 
	
	public static final String SEND_MY_SERVICE_DATA = "android.intent.action.my_service_data"; 
	
	private BroadcastReceiver receiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (SEND_MY_SERVICE_DATA_EXECUTE.equals(intent.getAction()))
			{
				DataSerializable parcelableData = (DataSerializable) intent.getSerializableExtra(Constants.PassDataKey.SERIALIZABLE);  
				DataSerializable data = getExectueValue(parcelableData);
				Intent intent1 = new Intent(MyService.SEND_MY_SERVICE_DATA);
				intent1.putExtra(Constants.PassDataKey.SERIALIZABLE, data);
				sendBroadcast(intent1);
			}
		}
	};
	
	private DataSerializable getExectueValue(DataSerializable data){
		data.id = 007;
		data.name = "MyService";
		return data;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.e("IBinder", "------------MyService-onBind");
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();	
		Log.e("Service", "-----------MyService-onCreate");
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(SEND_MY_SERVICE_DATA_EXECUTE);
		try {
			registerReceiver(receiver, filter);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Log.e("Service", "-----------MyService-onStart");
	}

	@SuppressLint("NewApi")
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub		
		Log.e("Service", "-----------MyService-onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.e("Service", "-----------MyService-onDestroy");
		
		unregisterReceiver(receiver);
		
		super.onDestroy();
	}
	

}
